package cn.cuilan.common.utils;

import cn.cuilan.common.entity.HttpEntity;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP请求响应处理
 *
 * @author zhang.yan
 * @date 2020/3/27
 */
@Slf4j
public class HttpHelper {

    private final OkHttpClient httpClient = new OkHttpClient();

    public HttpEntity get(String url) throws IOException {
        return doRequest(url, null, false, null);
    }

    public HttpEntity get(String url, Map<String, String> requestHeaders) throws IOException {
        return doRequest(url, requestHeaders, false, null);
    }

    public HttpEntity post(String url, Map<String, String> params) throws IOException {
        return doRequest(url, null, true, params);
    }

    public HttpEntity post(String url, Map<String, String> requestHeaders, Map<String, String> params) throws IOException {
        return doRequest(url, requestHeaders, true, params);
    }

    /**
     * 核心发送请求方法
     *
     * @param url            url
     * @param requestHeaders 请求头
     * @param isPost         是否为POST请求
     * @param postParams     POST请求参数
     * @throws IOException IO异常
     */
    private HttpEntity doRequest(String url, Map<String, String> requestHeaders, boolean isPost, Map<String, String> postParams) throws IOException {
        log.info("【Request URL】: {}", url);
        log.info("【Request Method】: {}", isPost ? "POST" : "GET");
        log.info("--------------------------------------------------------------------------------");

        // request header
        Headers.Builder headerBuilder = new Headers.Builder();
        if (requestHeaders != null && !requestHeaders.isEmpty()) {
            for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
                headerBuilder.add(entry.getKey(), entry.getValue());
            }
        }
        Headers headers = headerBuilder.build();

        // request
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url).headers(headers);
        if (isPost) {
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            if (postParams != null && !postParams.isEmpty()) {
                for (Map.Entry<String, String> entry : postParams.entrySet()) {
                    formBodyBuilder.add(entry.getKey(), entry.getValue());
                }
            }
            RequestBody requestBody = formBodyBuilder.build();
            requestBuilder.post(requestBody);

            // TODO 支持
            MultipartBody.Builder builder = new MultipartBody.Builder();
        }
        Request request = requestBuilder.build();

        // 执行请求并得到响应
        Response response = httpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
            log.error("http request error, url: {}", url);
            throw new IOException();
        }
        // 响应头
        Headers responseHeaders = response.headers();
        Map<String, String> resultHeaders = new HashMap<>();
        log.info("【Response Headers】");
        for (int i = 0; i < responseHeaders.size(); i++) {
            log.info("{}: {}", responseHeaders.name(i), responseHeaders.value(i));
            resultHeaders.put(responseHeaders.name(i), responseHeaders.value(i));
        }
//        log.info("--------------------------------------------------------------------------------");
//        log.info("【Response】");
//        log.info(Objects.requireNonNull(response.body()).string());
//        log.info("--------------------------------------------------------------------------------");

        HttpEntity httpEntity = new HttpEntity();
        httpEntity.setMethod(isPost ? "POST" : "GET");
        httpEntity.setHeaders(resultHeaders);
        ResponseBody body = response.body();
        if (body != null) {
            httpEntity.setBody(body.bytes());
        }
        return httpEntity;
    }
}
